<template>
        <vxe-modal v-model="dialogVisible" :loading="uploadLoading" title="请选择文件" width="700" :zIndex="2000" destroy-on-close :show-close="true" @close="closeVisible">
            <template v-slot>
                <el-upload ref="encryptionUpLoad"
                           action="uploadUrl"
                           :show-file-list="false"
                           :multiple="isMultiple"
                           :disabled="uploadFilesList.length === limit"
                           :limit="limit"
                           :on-change="handleChange"
                           :auto-upload="false"
                           :http-request="httpRequest"
                           :file-list="uploadFiles"
                           :accept="acceptType"
                           :on-exceed="fileExceed">
                    <el-button slot="trigger" size="mini" :disabled="uploadFilesList.length === limit" type="primary">选择文件</el-button>
                    <el-button style="margin-left: 10px;" size="mini" :disabled="uploadFiles.length == 0" type="success" @click="submitUpload">上传到服务器</el-button>
                </el-upload>
                <el-table :data="uploadFilesList" style="width: 100%;margin-top:10px" height="450">
                    <el-table-column prop="name" :show-overflow-tooltip="true" label="名称" width="320">
                        <template slot-scope="scope">
                            <i style="color:#409EFF" class=" el-icon-s-order" />
                            {{ scope.row.name }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" label="是否成功" width="140">
                        <template slot-scope="scope">
                            <template v-if="scope.row.status==='success'">
                                <div style="color:green">上传成功！</div>
                            </template>
                            <template v-else-if="scope.row.status != 'success' && scope.row.status != 'uploading'">
                                <div style="color:red">{{ scope.row.status }}</div>
                            </template>
                            <el-progress v-else :percentage="scope.row.progress" />
                        </template>
                    </el-table-column>
                    <el-table-column width="100" prop="size" label="文件大小" />
                    <!--<el-table-column prop="name" width="150" :show-overflow-tooltip="true" label="密级">
                        <template slot-scope="scope">
                            <el-select v-model="scope.row.securityLevel" :disabled="scope.row.status==='success'" placeholder="请选择" :popper-append-to-body="false" @change="selectSecurityLevel(scope.row)">
                                <el-option v-for="item in mjOptions"
                                           :key="item.value"
                                           :label="item.label"
                                           :value="item.value">
                                </el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" width="150" :show-overflow-tooltip="true" label="保密期限">
                        <template slot-scope="scope">
                            <el-input size="small" type="number" min="0" :disabled="scope.row.status==='success'" v-model="scope.row.securityPeriod" placeholder="请输入">
                                <i slot="suffix" style="font-style:normal;margin-right: 10px; line-height: 30px; color: #1e1e1e">(年)</i>
                            </el-input>
                        </template>
                    </el-table-column>-->
                    <el-table-column prop="name" width="100" :show-overflow-tooltip="true" label="功能">
                        <template slot-scope="scope">
                            <el-button type="primary" size="mini" :disabled="scope.row.status === 'success'" @click="handleRemove(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <!--<div v-if="hasChild" class="size14">注意：上传文件时会在当前船、当前类型下检查文件名称是否重复</div>-->
                <div class="modal_footer">
                    <vxe-button status="primary" content="关 闭" size="small" @click="closeVisible" />
                </div>
            </template>
        </vxe-modal>
</template>

<script>
    //import currencyJson from '../../common/json/currency.js'
    export default {
        components: {
        },
        props: {
            isMultiple: { type: Boolean, default: false },
            limit: { type: Number, default: 100 },
            fatherID: { type: Object, default: null },
            fileTypeInfo: { type: Number, default: null },
            uploadUrl: { type: Object, default: null },
            isCountRows: { type: Boolean, default: false },
        },
        data() {
            return {
                //currencyJson,
                dialogVisible: false,
                fileList: [],
                uploadFilesList: [],
                uploadFiles: [],
                securityLevel: null,
                mjOptions: [],
                securityPeriod: null,
                uploadLoading: false,
                acceptType: '',
                userMj:0
            };
        },
        mounted() {
            var _this = this;
           
            window.onresize = () => {
                return (() => {
                    _this.tableH = window.innerHeight - topBarHeight - 80;
                })();
            };
        },
        beforeDestroy() {
            window.onresize = null;
        },
        methods: {
            async show() {
                this.isCountRows === true ? this.acceptType = '.xls,.xlsx' : this.acceptType = '';
                //var mj = await this.getUserSeclevelList();
                //this.mjOptions = mj ? this.currencyJson.mjOptions.filter(e => e.value <= Number(mj)) : [];
                this.dialogVisible = true;
            },
            //getUserSeclevelList() {
            //    return new Promise((resolve) => {
            //        getUserSeclevel().then(res => {
            //            console.log('getUserSeclevel', res);
            //            this.userMj = res;
            //            resolve(res);
            //        }).catch(() => {
            //            resolve(undefined);
            //        });
            //    });
            //},
            showProgress(file, parms) {
                const { progress, status } = parms;
                const arr = [...this.uploadFilesList].map(items => {
                    if (items.uid === file.uid) {
                        items.progress = progress;
                        items.status = status;
                    };
                    return items;
                })
                this.uploadFilesList = [...arr];
            },
            async httpRequest(row) {
                this.uploadLoading = true;
                var file = row.file;
                var securityLevel = this.uploadFilesList.find(x => x.uid === file.uid).securityLevel;
                var securityPeriod = this.uploadFilesList.find(x => x.uid === file.uid).securityPeriod;
                var obj = {
                    "id": this.fatherID,
                    "filetype": this.fileTypeInfo,
                    "securityLevel": securityLevel,
                    "securityPeriod": Number(securityPeriod)
                };
                console.log(obj, this.uploadUrl);
                var form = new FormData();
                form.append('filename', file);
                let progress = 0;
                var imageUpload = params => {
                    return axios.post(this.uploadUrl + JSON.stringify(obj), params, {
                        headers: { 'content-type': 'multipart/form-data', 'Authorization': sessionStorage.getItem('token') }
                    })
                };
                imageUpload(form).then(res => {
                    var parms = {
                        progress, status: 'success'
                    };
                    this.uploadLoading = false;
                    this.showProgress(file, parms);
                }).catch(err => {
                    var parms = {
                        progress, status: err.response ? err.response.data : '上传失败!'
                    };
                    this.uploadLoading = false;
                    this.showProgress(file, parms);
                })
            },
            submitUpload() {
                //if (this.uploadFilesList.findIndex(x => x.securityLevel === null) > -1) {
                //    this.$message({ type: 'warning', message: '请先设置文件密级!' });
                //    return;
                //};

                const ids = this.uploadFilesList.map(value => value.name);
                const idsSet = new Set(ids);
                if (idsSet.size !== ids.length) {
                    this.$message({ type: 'warning', message: '文件名重复!' });
                    return;
                };
                this.$refs.encryptionUpLoad.submit();
                this.$refs.encryptionUpLoad.clearFiles();
                this.uploadFiles = [];
            },
            handleChange(file, fileList) {
                if (this.isCountRows) {
                    const files = file.raw
                    const reader = new FileReader();
                    reader.readAsBinaryString(files);
                    reader.onload = ev => {
                        try {
                            const f = ev.target.result;
                            const workbook = XLSX.read(f, { type: "binary" });
                            const wsname = workbook.SheetNames[0]; //取到第一个Sheet页
                            const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname], { header: 1, defval: '#' });
                            //至此，将拿到excel工作簿中的数据，下面就可以自己操作了
                            //........
                            console.log(ws);
                            this.$confirm(`当前文件共有 ${ws.length}行数据,是否继续上传?`, '提示', {
                                confirmButtonText: '确定',
                                cancelButtonText: '取消',
                                type: 'warning'
                            }).then(() => {
                                const fileList22 = {};
                                for (const key in file) {
                                    fileList22[key] = file[key]
                                };
                                // status:uploading、success、error 文件上传状态
                                // progress 文件上传进度
                                var name = fileList22.name;
                                var securityLevel = name.indexOf('非密') != -1 ? 1 :
                                    name.indexOf('内部') != -1 ? 2 :
                                        name.indexOf('MM') != -1 ? 3 :
                                            name.indexOf('JM') != -1 ? 4 :
                                                name.indexOf('JM') != -1 ? null : 1;
                                var securityPeriod = name.indexOf('非密') != -1 ? 0 :
                                    name.indexOf('内部') != -1 ? 0 :
                                        name.indexOf('MM') != -1 ? 10 :
                                            name.indexOf('JM') != -1 ? 20 :
                                                name.indexOf('JM') != -1 ? null : null;
                                if (securityLevel > this.userMj) {
                                    securityLevel = null;
                                    securityPeriod = null
                                };
                                this.uploadFilesList.push({ ...fileList22, progress: 0, status: 'uploading', securityLevel: securityLevel, securityPeriod: securityPeriod });
                                this.uploadFiles = fileList;
                            }).catch(() => {
                                console.log(this.uploadFiles)
                            })
                        }
                        catch (e) {
                            console.log(e);
                            return false;
                        }
                    };
                } else {
                    const fileList22 = {};
                    for (const key in file) {
                        fileList22[key] = file[key]
                    };
                    // status:uploading、success、error 文件上传状态
                    // progress 文件上传进度
                    var name = fileList22.name;
                    var securityLevel = name.indexOf('非密') != -1 ? 1 :
                        name.indexOf('内部') != -1 ? 2 :
                            name.indexOf('MM') != -1 ? 3 :
                                name.indexOf('JM') != -1 ? 4 :
                                    name.indexOf('JM') != -1 ? null : 1;
                    var securityPeriod = name.indexOf('非密') != -1 ? 0 :
                        name.indexOf('内部') != -1 ? 0 :
                            name.indexOf('MM') != -1 ? 10 :
                                name.indexOf('JM') != -1 ? 20 :
                                    name.indexOf('JM') != -1 ? 0 : 0;
                    if (securityLevel > this.userMj) {
                        securityLevel = null;
                        securityPeriod = null
                    };
                    this.uploadFilesList.push({ ...fileList22, progress: 0, status: 'uploading', securityLevel: securityLevel, securityPeriod: securityPeriod });
                    this.uploadFiles = fileList;
                }
            },
            selectSecurityLevel(row) {
                row.securityLevel <= 2 ?
                    row.securityPeriod = 0 :
                    row.securityLevel === 3 ?
                        row.securityPeriod = 10 :
                        row.securityLevel === 4 ?
                            row.securityPeriod = 20 : ''
            },
            handleRemove(row) {
                this.uploadFilesList.splice(this.uploadFilesList.indexOf(row), 1);
                this.uploadFiles.splice(this.uploadFiles.indexOf(row), 1);
            },
            closeVisible() {
                this.$emit('uploadOver', this.uploadFilesList);
                this.uploadFilesList = [];
                this.uploadFiles = [];
                this.$refs.encryptionUpLoad.clearFiles();
                this.dialogVisible = false;
                //this.getFiles(0);
            },
            // 文件超出上传个数限制的钩子
            fileExceed(files, fileList) {
                this.$message({ type: 'warning', message: '超出文件上传单次个数限制!' });
            },
            format(ops, op, hasops) {
                var val = null;
                if (hasops) {
                    var options = ops
                        .map((e) => {
                            return e.options;
                        })
                        .flat()
                        .valueOf();
                    val = options.find((e) => e.value === op);
                } else {
                    val = ops.find((e) => e.value === op);
                }
                return val ? val.label : "";
            },
            toDate(date) {
                return date ? moment(date).format("YYYY-MM-DD HH:mm:ss") : "";
            },
        },
        template: "#template",
    };
</script>
